<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <meta
      http-equiv="Cache-Control"
      content="no-cache, no-store, must-revalidate"
    />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <title>武汉一中90周年</title>
    <style>
      body {
        margin: 0;
        width: 100vw;
        height: 100vh;
        background: -webkit-linear-gradient(
          #c94a33,
          #6f2522
        ); /* Safari 5.1 - 6.0 */
        background: -o-linear-gradient(
          #c94a33,
          #6f2522
        ); /* Opera 11.1 - 12.0 */
        background: -moz-linear-gradient(
          #c94a33,
          #6f2522
        ); /* Firefox 3.6 - 15 */
        background: linear-gradient(#c94a33, #6f2522); /* 标准的语法 */
        -moz-user-select: none;
        -webkit-user-select: none;
        user-select: none;
      }
      .avatar-main {
        width: 80%;
        margin-top: 20px;
        margin-left: 10%;
        display: flex;
        flex-flow: row wrap;
      }
      .avatar {
        box-sizing: border-box;
        width: 40%;
        padding: 8px;
        border-radius: 10px;
        margin: 4vw 5%;
        display: inline-block;
        background-color: #fff;
        font-size: 0;
        /* border: 3px solid #fff; */
        position: relative;
        overflow: hidden;
      }
      .active {
        /* border: 3px solid #a93632; */
      }
      .avatar .img {
        width: 100%;
        pointer-events: none;
      }
      .avatar .choose {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 30px;
        display: none;
      }
      .active .choose {
        display: inline-block;
      }
      .download-img {
        width: 180px;
        height: 180px;
        /* border-radius: 40px; */
        overflow: hidden;
        margin: 0 auto;
        font-size: 0;
        position: relative;
      }
      #avatar {
        width: 160px;
        margin: 10px;
      }
      #border {
        width: 180px;
        position: absolute;
        top: 0;
        left: 0;
      }
      .avatar-top {
        padding-top: 30px;
        padding-bottom: 10px;
      }
      canvas {
        display: none;
      }
      .btn {
        width: 70%;
        height: 50px;
        margin-left: 15%;
        margin-top: 20px;
        text-align: center;
        background-color: #c94a33;
        color: white;
        line-height: 50px;
        border-radius: 25px;
      }
      .choose_wrapper {
        position: relative;
        width: 50%;
        height: 40px;
        margin-left: 25%;
        /* margin-top: 20px; */
        line-height: 40px;
      }
      .chooseImg {
        position: absolute;
        z-index: 10;
        width: 100%;
        height: 40px;
        text-align: center;
        background-color: #c94a33;
        color: white;
        border-radius: 25px;
      }
      .choose_wrapper input {
        position: absolute;
        width: 100%;
        height: 40px;
        line-height: 40px;
        z-index: 19;
        text-align: center;
        /* visibility: hidden; */
        opacity: 0;
      }
      input {
        -webkit-appearance: none;
      }
      #cav {
        position: absolute;
        top: -10000px;
      }
      #cavsImg {
        width: 180px;
      }
    </style>
  </head>
  <body>
    <div class="avatar-top">
      <div class="download-img" id="cav">
        <!-- <canvas id="myCanvas"></canvas> -->
        <img
          id="avatar"
          crossorigin="anonymous"
          src="images/user@2x.png"
          alt=""
        />
        <img id="border" crossorigin="anonymous" src="" alt="" />
      </div>
      <div class="download-img">
        <img
          id="cavsImg"
          crossorigin="anonymous"
          src="images/user@2x.png"
          alt=""
        />
      </div>
    </div>
    <div
      style="
        color: #fff;
        text-align: center;
        font-size: 18px;
        margin-bottom: 10px;
      "
    >
      长按头像保存至手机
    </div>
    <div class="choose_wrapper">
      <div class="chooseImg">选择其它照片制作头像</div>
      <input type="file" accept="image/*" />
    </div>
    <div class="avatar-main">
      <div id="avatar1" class="avatar">
        <img
          class="img"
          crossorigin="anonymous"
          id="a1"
          src="images/avatar1@3x.png"
          alt=""
        />
        <img
          class="choose"
          crossorigin="anonymous"
          src="images/choose@4x.png"
          alt=""
        />
      </div>
      <div id="avatar2" class="avatar">
        <img
          class="img"
          crossorigin="anonymous"
          id="a2"
          src="images/avatar2@3x.png"
          alt=""
        />
        <img
          class="choose"
          crossorigin="anonymous"
          src="images/choose@4x.png"
          alt=""
        />
      </div>
      <div id="avatar3" class="avatar">
        <img
          class="img"
          crossorigin="anonymous"
          id="a3"
          src="images/avatar3@3x.png"
          alt=""
        />
        <img
          class="choose"
          crossorigin="anonymous"
          src="images/choose@4x.png"
          alt=""
        />
      </div>
      <div id="avatar4" class="avatar">
        <img
          class="img"
          crossorigin="anonymous"
          id="a4"
          src="images/avatar4@3x.png"
          alt=""
        />
        <img
          class="choose"
          crossorigin="anonymous"
          src="images/choose@4x.png"
          alt=""
        />
      </div>
    </div>
  </body>
  <!-- <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->
  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="images/html2canvas.min.js"></script>
  <script>
    var imgSrc = "images/user@2x.png";
    var borderSrc = "";
    var iosBol = false;
    // if (imgSrc) {
    //   $("#avatar").attr("src", imgSrc)
    //   $("#cavsImg").attr("src", imgSrc)
    // }

    // var code = getQueryVariable("code")
    function isIos() {
      var u = navigator.userAgent;
      if (u.indexOf("iPhone") > -1 || u.indexOf("iOS") > -1) {
        return true;
      }
      return false;
    }
    $(function () {
      var target = document.getElementById("cav");

      var code = getQueryVariable("code");

      iosBol = isIos();
      console.log(code);
      if (window.sessionStorage.getItem("headimg")) {
        imgSrc = window.sessionStorage.getItem("headimg");
        $("#avatar").attr("src", imgSrc);
        $("#cavsImg").attr("src", imgSrc);
      } else {
        $.ajax({
          type: "GET",
          url: "https://avatar.jiuluzhai.top/api/v1/wechat/user",
          data: {
            code: code,
          },
          dataType: "json",
          success: function (res) {
            if (res.data.headimgurl) {
              imgSrc = res.data.headimgurl;
              window.sessionStorage.setItem("headimg", imgSrc);
              $("#avatar").attr("src", imgSrc);
              $("#cavsImg").attr("src", imgSrc);
            }
          },
        });
      }
    });

    $(".avatar").click(function (e) {
      console.log(e);
      console.log(iosBol);
      // alert(iosBol)
      $(".avatar").attr("class", "avatar");
      e.currentTarget.className = "avatar active";
      borderSrc = e.currentTarget.children[0].currentSrc;
      // alert(borderSrc)
      $("#border").attr("src", borderSrc);
      // if (iosBol) {
      //   drawAndShareImage(borderSrc)
      // } else {
      html2canvas(document.getElementById("cav"), {
        backgroundColor: null,
        allowTaint: true, ///允许跨域图片
        useCORS: true, //是否尝试使用CORS从服务器加载图像
        width: 180, //为了解决安卓手机截图后出现白边的问题
        height: 180, //为了解决安卓手机截图后出现白边的问题
      }).then((canvas) => {
        let databaseurl = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        // console.log(databaseurl)
        $("#cavsImg").attr("src", databaseurl);
      });
      // }
    });

    function getBase64(imgUrl, avatar) {
      window.URL = window.URL || window.webkitURL;
      var xhr = new XMLHttpRequest();
      xhr.open("get", imgUrl, true);
      // 至关重要
      xhr.responseType = "blob";
      var src = "";
      xhr.onload = function () {
        if (this.status == 200) {
          //得到一个blob对象
          var blob = this.response;
          console.log("blob", blob);
          // 至关重要
          let oFileReader = new FileReader();
          oFileReader.onloadend = function (e) {
            // 此处拿到的已经是 base64的图片了
            let base64 = e.target.result;
            console.log("方式一》》》》》》》》》", base64);
            // var img = document.getElementById("avatar");
            // img.src = base64
          };
          oFileReader.readAsDataURL(blob);
          //====为了在页面显示图片，可以删除====
          // $("#avatar").attr("src", img_src)
          var img = document.getElementById(avatar);
          img.onload = function (e) {
            window.URL.revokeObjectURL(img.src); // 清除释放
          };
          src = window.URL.createObjectURL(blob);
          img.src = src;
          console.log(src);
          // document.getElementById("bbt").appendChild(img);
          //====为了在页面显示图片，可以删除====
        }
      };
      xhr.send();
    }

    function drawAndShareImage(borderSrc) {
      // alert(123)
      var canvas = document.createElement("canvas");
      canvas.width = 360;
      canvas.height = 360;
      var context = canvas.getContext("2d");
      context.rect(0, 0, canvas.width, canvas.height);
      context.fillStyle = "#fff";
      context.fill();
      var myImage = new Image();
      myImage.src = imgSrc; //背景图片 你自己本地的图片或者在线图片
      myImage.crossOrigin = "Anonymous";
      // myImage.setAttribute('crossOrigin','anonymous')
      myImage.onload = function () {
        // alert(111)
        context.drawImage(myImage, 20, 20, 320, 320);
        // context.font = "30px Courier New";
        // context.fillText("我是文字",100,250);
        var myImage2 = new Image();
        myImage2.src = borderSrc; //你自己本地的图片或者在线图片
        myImage2.crossOrigin = "Anonymous";
        // myImage2.setAttribute('crossOrigin','anonymous')
        myImage2.onload = function () {
          context.drawImage(myImage2, 0, 0, 360, 360);
          // alert(321)
          var base64 = canvas.toDataURL("image/png"); //"image/png" 这里注意一下
          // $("#hh").html(base64)
          // alert(base64)
          var img = document.getElementById("cavsImg");
          // document.getElementById('avatar').src = base64;
          img.setAttribute("src", base64);
          // $("#cavsImg").attr("src", base64)
        };
      };
    }
    function downloadImg() {
      console.log(123);
      var imgUrl = $("#cavsImg")[0].src;
      console.log(imgUrl);
      // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
      if (window.navigator.msSaveOrOpenBlob) {
        var bstr = atob(imgUrl.split(",")[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        var blob = new Blob([u8arr]);
        window.navigator.msSaveOrOpenBlob(blob, "chart-download" + "." + "png");
      } else {
        // 这里就按照chrome等新版浏览器来处理
        var a = document.createElement("a");
        a.href = imgUrl;
        a.setAttribute("download", "chart-download");
        a.click();
      }
    }

    $("input[type='file']").change(function () {
      var file = this.files[0];
      console.log(file);
      if (window.FileReader) {
        console.log(222);
        var reader = new FileReader();
        reader.readAsDataURL(file);
        //监听文件读取结束后事件
        reader.onloadend = function (e) {
          // $(".weui_uploader_file").css("background-image","url("+e.target.result+")");
          imgSrc = e.target.result;
          $("#avatar").attr("src", imgSrc);
          // $("#cavsImg").attr("src", imgSrc)
          // if (iosBol) {
          //   drawAndShareImage(borderSrc)
          // } else {
          if (borderSrc) {
            html2canvas(document.getElementById("cav"), {
              backgroundColor: null,
              allowTaint: true, ///允许跨域图片
              useCORS: true, //是否尝试使用CORS从服务器加载图像
              width: 180, //为了解决安卓手机截图后出现白边的问题
              height: 180, //为了解决安卓手机截图后出现白边的问题
            }).then((canvas) => {
              let databaseurl = canvas.toDataURL("image/png"); //得到图片的base64编码数据
              // console.log(databaseurl)
              $("#cavsImg").attr("src", databaseurl);
            });
          } else {
            $("#cavsImg").attr("src", imgSrc);
          }
          // }
          // drawAndShareImage(borderSrc)
          //e.target.result就是最后的路径地址
        };
      }
    });

    function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return false;
    }
  </script>
</html>
